package cn.sofwin.blog.web;

import cn.sofwin.blog.dao.UserDao;
import cn.sofwin.blog.entity.User;
import cn.sofwin.blog.service.UserService;
import cn.sofwin.blog.service.impl.UserServiceImpl;
import cn.sofwin.blog.utils.HttpHelper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 控制器
 * @author zx
 * @since 1.0
 *
 */
@WebServlet("/blog/user/register")
public class RegisterServlet extends HttpServlet {

    private UserService userService = UserServiceImpl.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 转发到注册页面
        req.getRequestDispatcher("/register.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理注册请求
        HttpHelper.charset(req);
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String nickname = req.getParameter("nickname");

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            HttpHelper.error("用户名或密码错误",req,resp);
        }else {
            User user = userService.register(username,password,nickname);
            if (user == null){
                HttpHelper.error("该用户已存在",req,resp);
            }else {
                //重定向到登录页面（先进登录的servlet）
                resp.sendRedirect("/blog/user/login");
            }
        }
    }


}